package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.Socket.WebSocketServer;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.*;
import com.sky.entity.*;
import com.sky.exception.AddressBookBusinessException;
import com.sky.exception.OrderBusinessException;
import com.sky.exception.ShoppingCartBusinessException;
import com.sky.mapper.*;
import com.sky.result.PageResult;
import com.sky.result.Result;
import com.sky.service.OrderService;
import com.sky.utils.WeChatPayUtil;
import com.sky.vo.OrderPaymentVO;
import com.sky.vo.OrderStatisticsVO;
import com.sky.vo.OrderSubmitVO;
import com.sky.vo.OrderVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class OrderServiceImpl implements OrderService {
    @Autowired
    private AddressBookMapper addressBookMapper;
    @Autowired
    private ShoppingCartMapper shoppingCartMapper;
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private WeChatPayUtil weChatPayUtil;
    @Autowired
    private UserMapper userMapper;

    @Autowired
    private WebSocketServer webSocketServer;




    /**
     * 用户下单
     * @param ordersSubmitDTO
     * @return
     */
    @Override
    @Transactional
    public OrderSubmitVO submitOrder(OrdersSubmitDTO ordersSubmitDTO) {
        //1.先处理地址谱和购物车为空的情况
        AddressBook addressBook = addressBookMapper.getById(ordersSubmitDTO.getAddressBookId());
        if(addressBook==null){
            throw new AddressBookBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }

        Long userId = BaseContext.getCurrentId();
        ShoppingCart shoppingCart = new ShoppingCart();
        shoppingCart.setId(userId);
        List<ShoppingCart> shoppingCarts = shoppingCartMapper.list(shoppingCart);
        if(shoppingCarts==null || shoppingCarts.size()==0){
            throw new ShoppingCartBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        }

        //2.插入订单数据
        Orders order = new Orders();
        BeanUtils.copyProperties(ordersSubmitDTO,order);
        order.setUserId(userId);
        order.setOrderTime(LocalDateTime.now());
        order.setConsignee(addressBook.getConsignee());
        order.setPhone(addressBook.getPhone());
        order.setPayStatus(Orders.UN_PAID);
        order.setStatus(Orders.PENDING_PAYMENT);
        order.setNumber(String.valueOf(System.currentTimeMillis()));
        Long addressBookId = ordersSubmitDTO.getAddressBookId();
        AddressBook addressBook1 = addressBookMapper.getById(addressBookId);
        String add=addressBook1.getProvinceName()+" "+addressBook1.getCityName()+" "+addressBook1.getDistrictName()+" "+addressBook1.getDetail();
        order.setAddress(add);

        orderMapper.insert(order);
        //3.插入订单明细数据


        List<OrderDetail> orderDetailList=new ArrayList<>();

        for (ShoppingCart cart : shoppingCarts) {
            OrderDetail orderDetail = new OrderDetail();

            BeanUtils.copyProperties(cart,orderDetail);
            orderDetail.setOrderId(order.getId());//获得订单号
            orderDetailList.add(orderDetail);

        }

        orderDetailMapper.insertBatch(orderDetailList);
        //4.清空购物车

        shoppingCartMapper.clean(userId);
        //5.封装VO对象
        OrderSubmitVO orderSubmitVO = OrderSubmitVO.builder()
                .id(order.getId())
                .orderTime(order.getOrderTime())
                .orderNumber(order.getNumber())
                .orderAmount(order.getAmount()).build();


        return orderSubmitVO;
    }


    /**
     * 订单支付
     *
     * @param ordersPaymentDTO
     * @return
     */
    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) throws Exception {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();
        User user = userMapper.getById(userId);

        //调用微信支付接口，生成预支付交易单
        JSONObject jsonObject = weChatPayUtil.pay(
                ordersPaymentDTO.getOrderNumber(), //商户订单号
                new BigDecimal(0.01), //支付金额，单位 元
                "苍穹外卖订单", //商品描述
                user.getOpenid() //微信用户的openid
        );

        if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
            throw new OrderBusinessException("该订单已支付");
        }

        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
        vo.setPackageStr(jsonObject.getString("package"));

        return vo;
    }

    /**
     * 支付成功，修改订单状态
     *
     * @param outTradeNo
     */
    public void paySuccess(String outTradeNo) {

        // 根据订单号查询订单
        Orders ordersDB = orderMapper.getByNumber(outTradeNo);

        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.TO_BE_CONFIRMED)
                .payStatus(Orders.PAID)
                .checkoutTime(LocalDateTime.now())
                .build();

        orderMapper.update(orders);

        Map map = new HashMap();
        map.put("type",1);
        map.put("orderId",ordersDB.getId());
        map.put("content","订单号："+outTradeNo);
        String jsonString = JSON.toJSONString(map);
        webSocketServer.sendToAllClient(jsonString);
    }

    /**
     * 用户端订单分页查询
     *
     * @param pageNum
     * @param pageSize
     * @param status
     * @return
     */
    public PageResult pageQuery4User(int pageNum, int pageSize, Integer status) {
        // 设置分页
        PageHelper.startPage(pageNum, pageSize);

        OrdersPageQueryDTO ordersPageQueryDTO = new OrdersPageQueryDTO();
        ordersPageQueryDTO.setUserId(BaseContext.getCurrentId());
        ordersPageQueryDTO.setStatus(status);

        // 分页条件查询
        Page<Orders> page = orderMapper.pageQuery(ordersPageQueryDTO);

        List<OrderVO> list = new ArrayList();

        // 查询出订单明细，并封装入OrderVO进行响应
        if (page != null && page.getTotal() > 0) {
            for (Orders orders : page) {
                Long orderId = orders.getId();// 订单id

                // 查询订单明细
                List<OrderDetail> orderDetails = orderDetailMapper.getByOrderId(orderId);
                OrderVO orderVO = new OrderVO();
                BeanUtils.copyProperties(orders, orderVO);
                orderVO.setOrderDetailList(orderDetails);

                list.add(orderVO);
            }
        }
        return new PageResult(page.getTotal(), list);
    }

    /**
     * 通过订单id查询订单详细信息
     * @param id
     * @return
     */
    public OrderVO selectById(Long id) {
        OrderVO orderVO = new OrderVO();
        Long userId = BaseContext.getCurrentId();
        Orders orders = new Orders();
        orders.setUserId(userId);
        orders.setId(id);
        orders=orderMapper.getById(orders);
        BeanUtils.copyProperties(orders,orderVO);


        List<OrderDetail> orderDetailList = orderDetailMapper.getByOrderId(id);

        orderVO.setOrderDetailList(orderDetailList);


        return orderVO;
    }

    /**
     * 取消订单
     * @param id
     */
    public void cancelOrder(Long id) {
        Orders order = new Orders();
        Long userId = BaseContext.getCurrentId();
        order.setUserId(userId);
        order.setId(id);
        order.setStatus(Orders.CANCELLED);
        orderMapper.updateOrderStatueById(order);

    }

    /**
     * 再来一单
     * @param id
     */
    public void repetitionOrder(Long id) {
        Orders orders = new Orders();
        orders.setId(id);
        Long userId = BaseContext.getCurrentId();
        orders.setUserId(userId);
        orders = orderMapper.getById(orders);
        List<OrderDetail> detailList = orderDetailMapper.getByOrderId(id);
        orderDetailMapper.insertBatch(detailList);
        orderMapper.insert(orders);

    }

    /**
     * 订单分页查询
     * @param ordersPageQueryDTO
     * @return
     */
    @Transactional
    public PageResult page(OrdersPageQueryDTO ordersPageQueryDTO) {
        PageHelper.startPage(ordersPageQueryDTO.getPage(),ordersPageQueryDTO.getPageSize());
        Page<Orders> page=orderMapper.getOrders(ordersPageQueryDTO);


        return new PageResult(page.getTotal(),page.getResult());
    }

    /**
     * 各个状态的订单数量统计
     * @return
     */
    public OrderStatisticsVO getStatistic() {

        //待接单数量
        Integer toBeConfirmed=orderMapper.getToBeConfirmed(Orders.TO_BE_CONFIRMED);
        //派送中数量
        Integer  deliveryInProgress =orderMapper.getDeliveryInProgress(Orders.DELIVERY_IN_PROGRESS);
        //待派送数量
        Integer confirmed= orderMapper.getConfirmed(Orders.CONFIRMED);

        OrderStatisticsVO orderStatisticsVO = new OrderStatisticsVO();
        orderStatisticsVO.setConfirmed(confirmed);
        orderStatisticsVO.setToBeConfirmed(toBeConfirmed);
        orderStatisticsVO.setDeliveryInProgress(deliveryInProgress);


        return orderStatisticsVO;
    }

    /**
     * 查询订单详情
     * @param id
     * @return
     */
    @Transactional
    public OrderVO getDetail(Long id) {
        OrderVO orderVO = new OrderVO();
        //Long userId = BaseContext.getCurrentId();
        Orders orders = new Orders();
        //orders.setUserId(userId);
        orders.setId(id);
        orders=orderMapper.getById(orders);
        BeanUtils.copyProperties(orders,orderVO);


        List<OrderDetail> orderDetailList = orderDetailMapper.getByOrderId(id);

        orderVO.setOrderDetailList(orderDetailList);


        return orderVO;



    }


    /**
     * 将订单状态更改为接单成功
     */
    @Override
    public void updateStatusToConfirms(Long id) {

        orderMapper.upDateToConfirms(id);
    }

    /**
     * 将订单状态更改为派送中
     * @param id
     */
    @Override
    public void updateStatusTodelivery(Long id) {
        orderMapper.upToDelivery(id);

    }

    /**
     * 将订单状态更改为拒绝
     * @param ordersRejectionDTO
     */
    public void updateStatusToRejection(OrdersRejectionDTO ordersRejectionDTO) {

        orderMapper.updateToRejection(ordersRejectionDTO);

    }

    /**
     * 把订单状态更改为已取消
     * @param ordersCancelDTO
     */
    public void updateStatusToCancel(OrdersCancelDTO ordersCancelDTO) {

        orderMapper.updateToCancel(ordersCancelDTO);
    }

    /**
     * 把订单状态更改为完成
     * @param id
     */
    public void updateStatusToComplete(Long id) {
        orderMapper.updateToComplete(id);

    }

    /**
     * 客户催单
     * @param id
     */
    public void reminder(Long id) {
        Orders orders1 = new Orders();
        orders1.setId(id);
        Orders orders = orderMapper.getById(orders1);
        if(orders==null){
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        Map map=new HashMap();
        map.put("type",2);
        map.put("orderId",id);
        map.put("content","订单号："+orders.getNumber());
        webSocketServer.sendToAllClient(JSON.toJSONString(map));


    }


}
